//
//  loginAndRegister.swift
//  万才信息App
//
//  Created by 陌上互联  on 16/7/13.
//  Copyright © 2016年 万才信息. All rights reserved.
//

import Foundation

//登录与注册
class loginAndRegister {
    
    private static let ASMX_NAME="LoginAndRegiste.asmx"
    
    private static let REGISTER_METHOD="UserRegister"
    private static let LOGIN_METHOD="MyLogin"
    
    private static let LOGIN_SUCCESS_MSG="用户登录成功！"
    private static let REGISTER_SUCCESS_MSG="用户注册成功！"
    
//    用户注册
    static func userRegister(uName:String,pwd:String,email:String,
                      successCallback:(userId:NSNumber!)->Void,
                      failCallback:(error:String!)->Void){
        let mySoap=soapUtil()
        
        mySoap.setName(ASMX_NAME, methodName: REGISTER_METHOD)
        
        mySoap.addParam("uName", value: uName)
        mySoap.addParam("pwd", value: pwd)
        mySoap.addParam("email", value: email)
        
        mySoap.send({ (data :JSON) in
            if let result=data["result"].string {
                if result=="true"{
//                    成功
                    let msg=data["msg"].string
                    if msg==REGISTER_SUCCESS_MSG{
//                        存储userId
                        userUtil.storeCurrUserId(String(data["userId"].number!))
                        userUtil.storeCurrUserName(uName)
                        successCallback(userId: data["userId"].number)
                    }else{
                        failCallback(error: msg)
                    }
                    
                }else{
//                    失败
                    failCallback(error: "注册失败")
                }
            }
            }) { (error) in
                failCallback(error: "注册失败")
        }
    }
    
//    用户登录
    static func userLogin(uName:String,pwd:String,
                   successCallback:(userId:NSNumber!)->Void,
                   failCallback:(error:String!)->Void
                   ){
        let mySoap=soapUtil()
        
        mySoap.setName(ASMX_NAME, methodName: LOGIN_METHOD)
        
        mySoap.addParam("uName", value: uName)
        mySoap.addParam("pwd", value: pwd)
        
        mySoap.send({ (data) in
            if let result=data["result"].string{
                if result=="true"{
                    let msg=data["msg"].string
                    if msg==LOGIN_SUCCESS_MSG {
//                        存储userId
                        userUtil.storeCurrUserId(String(data["userId"].number!))
                        userUtil.storeCurrUserName(uName)
                        successCallback(userId: data["userId"].number)
                    }else{
                        failCallback(error: msg)
                    }
                }else{
                    failCallback(error: data["msg"].string)
                }
            }
            }) { (error) in
                print("登录出错")
                failCallback(error: "登录失败")
        }
    }
    
    
}